package cn.epsilon3.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSONObject;
import cn.epsilon3.constant.HttpMethodEnum;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;

/**
 * 网络请求工具类
 *
 * @author epsilon3
 * @date 2023-05-05
 */
public class HttpUtils {

    private static final Log log = LogFactory.get();

    public static com.alibaba.fastjson2.JSONObject sendHttp(HttpMethodEnum type, String url, HashMap<String, String> headers, JSONObject bodyJson) {

        HttpRequest httpRequest = null;

        switch (type) {
            case GET:
                httpRequest = HttpRequest.get(url);
                break;
            case POST:
                httpRequest = HttpRequest.post(url);
                break;
        }

        Iterator<String> iterator = headers.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = headers.get(key);
            httpRequest.header(key,value);
        }

        String result = httpRequest.body(bodyJson.toString())
                .execute()
                .body();
        com.alibaba.fastjson2.JSONObject jsonObject = com.alibaba.fastjson2.JSONObject.parseObject(result);

        log.info("HTTP请求：{}，返参：{}",httpRequest,jsonObject);

        return jsonObject;
    }

    public static String getIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }
}
